﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using CommonTools;
using StationDemo.FrameUI;
using BaseDll;
using MotionIoLib;
using System.Threading;
using OtherDevice;
using UserData;
using Language;
using CommonDlg;
using HY_DynamicPassword;
using static UserData.Control_ScrewData;
using TestResult = UserData.TestResult;

namespace StationDemo
{
    public partial class Form1 : UIHeaderMainFrame
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void WndProc(ref Message m)
        {

            if (m.Msg == 163 && m.WParam.ToInt32() == 1)
                return;

            base.WndProc(ref m);


        }
        Form_正在复位 formHome = new Form_正在复位();

        public delegate void EventShowHome(string strInfo, int n_Value);
        public static EventShowHome OnTest_ShowHome = null;

        private void Form1_Load(object sender, EventArgs e)
        {
            sys.g_eventRightChanged += ChangedUserRight;
            UserConfig.InitOtherParamter();
            AlarmMgr.GetIntance().Read();
            CommonDlg.AlarmInfoMannage.GetInstance().Read();
            foreach (var item in Enum.GetValues(typeof(AlarmList)))
            {
                CommonDlg.AlarmInfoMannage.GetInstance().AddAlarmInfo((int)item, item.ToString());

            }
            InitProductNum();
            InitHardWare();
            IOMgr.GetInstace().m_deltgateSystemSingl += ProcessSysIo;
            MotionMgr.GetInstace().m_eventAxisSingl += ProcessSysIo;
            IOMgr.GetInstace().m_eventIoInputChanageByName += ControlIOChanged;
            SoftVersionMgr.GetInstance().Load();
            SoftVersionMgr.GetInstance().Function_VersionCheck(this);
            //初始化SunnyUI
            IniSunnyUI();
            GlobalVariable.g_eventStationStateChanged += StationStateChangedHandler;
            GlobalVariable.g_StationState = StationState.StationStateEmg;
            OnTest_ShowHome += ShowHomeInfo;
            if (IOMgr.GetInstace().GetInputDic().ContainsKey("手自动按钮"))
                GlobalVariable.g_ControlMode = IOMgr.GetInstace().ReadIoInBit("手自动按钮") ? ControlMode.Auto : ControlMode.Manual;
            else
                GlobalVariable.g_ControlMode = ControlMode.None;

        }
        Form_Alarm alarm = null;
        public void ShowHomeInfo(string strInfo, int n_Value)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => ShowHomeInfo(strInfo, n_Value)));
            }
            else
            {
                formHome.InfoAndProcess(strInfo, n_Value);
            }

        }
        private void InitProductNum()
        {
            //读工站配置
            ConfigToolMgr.GetInstance().ReadStationConfig();
            //读取用户设置
            ConfigToolMgr.GetInstance().ReadUserConfig();

            ConfigToolMgr.GetInstance().ReadUserParam(Param_System.Instance);
            ParamSetMgr.GetInstance().SaveParam(Param_System.Instance);
          //  ParamSetMgr.GetInstance().SaveParam(Param_System.Instance);
            ConfigToolMgr.GetInstance().ReadRunRadioConfig();

            //读取产品文件
            ConfigToolMgr.GetInstance().ReadProductDir_Name();
            //读硬件配置 并创建IO,Motion 卡类 对象 并以默认参数配置卡
            ConfigToolMgr.GetInstance().ReadMotionCardConfig();
            ConfigToolMgr.GetInstance().ReadIoCardConfig();
            ConfigToolMgr.GetInstance().ReadIoInputConfig();
            ConfigToolMgr.GetInstance().ReadIoOutputConfig();
            //读取机器人数据
            ConfigToolMgr.GetInstance().ReadRobotConfig();
            ConfigToolMgr.GetInstance().ReadRobotIoInputConfig();
            ConfigToolMgr.GetInstance().ReadRobotIoOutputConfig();
            //读取六轴机器人数据
            ConfigToolMgr.GetInstance().ReadSixRobotConfig();
            ConfigToolMgr.GetInstance().ReadSixRobotIoInputConfig();
            ConfigToolMgr.GetInstance().ReadSixRobotIoOutputConfig();

            //添加工位
            UserConfig.AddStation();
            //读运动配置
            ConfigToolMgr.GetInstance().ReadMoveParamConfig();
            ConfigToolMgr.GetInstance().ReadHomeParamConfig();
            //初始化登入权限 
            User user = new User();
            int index = sys.g_listUser.FindIndex(t => t._userName == "admin");
            if (index == -1)
            {
                user = new User() { _userName = "admin", _userPassWord = "admin", _userRight = UserRight.Admin };
                sys.g_listUser.Add(user);
            }

        }
        private void InitHardWare()
        {
            try
            {
                //初始化IO Motion
                if (!MotionMgr.GetInstace().OpenAllCard())
                {
                    MessageBox.Show("初始化控制卡失败");
                }
                if (!IOMgr.GetInstace().initAllIoCard())
                {
                    MessageBox.Show("初始化IO卡失败");
                }
                //if (!RobotMotionMgr.GetInstace().InitRobotSystem())
                //{
                //    MessageBox.Show("初始化机器人失败");
                //}
                //if (!SixRobotMotionMgr.GetInstace().InitRobotSystem())
                //{
                //    MessageBox.Show("初始化六轴机器人失败");
                //}
                Safe.AddAllSafeCheck();
                UserConfig.ResetIO();
                DeviceMgr.GetInstance().Read();
                DeviceMgr.GetInstance().Function_动态创建设备();
                DeviceMgr.GetInstance().Init();
                ModuleUnit.ModuleMgr.GetInstance().Read();
                Thread.Sleep(500);
                LoadSeverMgr.Instance.Init();




            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }
        }
        StationState station_LastState = StationState.StationStateEmg;
        private void ProcessSysIo(string strIoName, bool bCurrentState)
        {
           

            if (strIoName.Contains("急停") && !bCurrentState)
            {
                if (IOMgr.GetInstace().Function_ReCheckIO(strIoName, false, 200))
                {
                    if (GlobalVariable.g_StationState == StationState.StationStateRun || GlobalVariable.g_StationState == StationState.StationStatePause)
                    {
                        MotionMgr.GetInstace().StopEmg();
                        StationMgr.GetInstance().Stop();
                        MotionMgr.GetInstace().StopEmg();
                    }
                    else
                    {
                        DoWhile.StopCirculate();
                        DoWhile.ResetCirculate();
                    }
                    AlarmMgr.GetIntance().WarnWithDlg((int)AlarmList.急停, new string[] { "退出" }, new string[] { "急停被按下!" });
                    GlobalVariable.g_StationState = StationState.StationStateEmg;
                }
            }
            if (strIoName.Contains("安全继电器") && bCurrentState)
            {
                if (IOMgr.GetInstace().Function_ReCheckIO(strIoName, true, 200))
                {
                    if (GlobalVariable.g_StationState == StationState.StationStateRun || GlobalVariable.g_StationState == StationState.StationStatePause)
                    {
                        MotionMgr.GetInstace().StopEmg();
                        StationMgr.GetInstance().Stop();
                        MotionMgr.GetInstace().StopEmg();
                    }
                    else
                    {
                        DoWhile.StopCirculate();
                        DoWhile.ResetCirculate();
                    }
                    AlarmMgr.GetIntance().WarnWithDlg((int)AlarmList.急停, new string[] { "退出" }, new string[] { "安全继电器触发，设备PowerOFF!" });
                    GlobalVariable.g_StationState = StationState.StationStateEmg;
                }
            }
            //if (strIoName == IO_IN.气源检测.ToString() && !bCurrentState)
            //{
            //    StationMgr.GetInstance().Pause();
            //    AlarmMgr.GetIntance().WarnWithDlg((int)AlarmList.气源检测, new string[] { "退出" }, null);
            //}
            if (strIoName.Contains("安全光栅"))
            {
                if (!GlobalVariable.启用安全光栅)
                    return;
                if (strIoName == "前门安全光栅1")
                    return;
                if (!bCurrentState)
                {
                    if (GlobalVariable.g_StationState == StationState.StationStateRun)
                    {
                        //进行信号滤波，防止感应器频闪
                        if (IOMgr.GetInstace().Function_ReCheckIO(strIoName, false, 200))
                        {
                            StationMgr.GetInstance().Pause();
                            AlarmMgr.GetIntance().WarnWithDlg((int)AlarmList.安全光栅, new string[] { "确认" }, new string[] { $"{strIoName}被触发，设备已暂停" });
                        }
                    }
                }
            }
            //if (strIoName.Contains("安全门"))
            //{
            //    if (!GlobalVariable.启用安全门)
            //        return;
            //    if (!bCurrentState)
            //    {
            //        if (GlobalVariable.g_StationState == StationState.StationStateRun)
            //        {//进行信号滤波，防止感应器频闪
            //            if (IOMgr.GetInstace().Function_ReCheckIO(strIoName, false, 200))
            //            {
            //                StationMgr.GetInstance().Pause();
            //                AlarmMgr.GetIntance().WarnWithDlg((int)AlarmList.安全光栅, new string[] { "确认" }, new string[] { $"{strIoName}已触发，设备已暂停" });
            //            }

            //        }
            //    }
            //}
        }

        private void ControlIOChanged(string strIoName, bool bCurrentState)
        {
            if (strIoName == "启动按钮" && bCurrentState)
            {
                if (IOMgr.GetInstace().Function_ReCheckIO(strIoName, bCurrentState) && GlobalVariable.g_ControlMode == ControlMode.Auto)
                {
                    if (GlobalVariable.g_StationState == StationState.StationStateStop)
                    {
                        if (AlarmMgr.GetIntance().IsAlarm())
                        {
                            StationStateHelper.OnTest_ShowStep("系统", "报警未清除，禁止启动", LogType.Err);
                            return;
                        }
                        if (!IsSafeDoorAndGrating())
                            return;
                        Header.SelectedIndex = 0;
                        Header.MouseUp += Header_MouseUp;
                        BaseDll.DeviceDataCollect.GetInstance().Function_ControlLog("主界面", "自动运行");
                        if (!UserConfig.Function_全机回零())
                        {
                            Header.MouseUp -= Header_MouseUp;
                            StationStateHelper.OnTest_ShowStep("系统", "全机回零失败，禁止启动", LogType.Err);
                            return;
                        }
                        Header.MouseUp -= Header_MouseUp;
                        if (!UserConfig.Funtion_运行前处理())
                            return;
                        StationMgr.GetInstance().Run();
                    }
                }
                else if (GlobalVariable.g_StationState == StationState.StationStatePause)
                {
                    if (AlarmMgr.GetIntance().IsAlarm())
                    {
                        UIMessageBox.ShowError("报警未清除，禁止启动");
                        return;
                    }
                    BaseDll.DeviceDataCollect.GetInstance().Function_ControlLog("主界面", "恢复运行");
                    if (!IsSafeDoorAndGrating())
                        return;
                    UserConfig.Funtion_恢复时处理();
                    StationMgr.GetInstance().Resume();
                }
            }
            if (strIoName == "停止按钮" && !bCurrentState)
            {
                if (IOMgr.GetInstace().Function_ReCheckIO(strIoName, bCurrentState, 500) && GlobalVariable.g_StationState == StationState.StationStateRun)
                {
                    BaseDll.DeviceDataCollect.GetInstance().Function_ControlLog("主界面", "暂停运行");
                    UserConfig.Funtion_暂停时处理();
                    StationMgr.GetInstance().Pause();
                }
            }
            if (strIoName == "复位按钮" && !bCurrentState)
            {
                if (IOMgr.GetInstace().Function_ReCheckIO(strIoName, bCurrentState, 2000)
                    && (GlobalVariable.g_StationState == StationState.StationStateEmg || GlobalVariable.g_StationState == StationState.StationStateStop)
                    && GlobalVariable.g_ControlMode == ControlMode.Auto)
                {
                    DeviceDataCollect.GetInstance().Function_ControlLog("主界面", "全机回零");
                    UserConfig.ResetIO();
                    GlobalVariable.g_StationState = StationState.StationStateHoming;
                    try
                    {
                        if (!IsSafeDoorAndGrating())
                            return;
                        Header.SelectedIndex = 0;
                        Header.MouseUp += Header_MouseUp;
                        StationStateHelper.OnTest_ShowStep("系统", "开始回零", LogType.Warn);
                        Task task = new Task(() =>
                        {
                            bool result = UserConfig.Function_全机回零();
                            if (result)
                            {
                                GlobalVariable.g_StationState = StationState.StationStateStop;
                                StationStateHelper.OnTest_ShowStep("系统", "回零成功", LogType.Info);
                            }
                            else
                            {
                                GlobalVariable.g_StationState = StationState.StationStateEmg;
                                StationStateHelper.OnTest_ShowStep("系统", "回零失败", LogType.Err);
                            }
                            BeginInvoke(new Action(() =>
                            {
                                Header.MouseUp -= Header_MouseUp;
                            }));

                        });
                        task.Start();
                    }
                    catch (Exception ex)
                    {
                        StationStateHelper.OnTest_ShowStep("系统", "回零失败", LogType.Err);
                        MessageBox.Show(ex.ToString());
                    }
                }

            }
            if (strIoName == "手自动切换")
            {
                if (IOMgr.GetInstace().Function_ReCheckIO(strIoName, bCurrentState))
                {
                    GlobalVariable.g_ControlMode = bCurrentState ? ControlMode.Auto : ControlMode.Manual;
                    if ((GlobalVariable.g_StationState == StationState.StationStateRun || GlobalVariable.g_StationState == StationState.StationStatePause)
                         && GlobalVariable.g_ControlMode == ControlMode.Manual)
                    {
                        StationMgr.GetInstance().Stop();
                        UserConfig.Funtion_停止时处理();
                    }
                    else if (GlobalVariable.g_ControlMode == ControlMode.Auto) //从手动切换到自动  状态转为Emg
                    {
                        GlobalVariable.g_StationState = StationState.StationStateEmg;
                    }

                }
            }

        }
        private bool IsSafeDoorAndGrating()
        {

            if (GlobalVariable.启用安全门)
            {
                if (IOMgr.GetInstace().GetOutputDic().ContainsKey("安全门") && !IOMgr.GetInstace().ReadIoInBit("安全门"))
                {
                    AlarmMgr.GetIntance().WarnWithDlg((int)AlarmList.安全门, new string[] { "退出" }, null);
                    return false;
                }
            }
            if (IOMgr.GetInstace().GetOutputDic().ContainsKey("气源检测") && IOMgr.GetInstace().GetInputDic().ContainsKey("气源检测"))
            {
                if (!IOMgr.GetInstace().ReadIoInBit("气源检测"))
                {
                    AlarmMgr.GetIntance().WarnWithDlg((int)AlarmList.气源检测, new string[] { "退出" }, null);
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 初始化SunnyUI
        /// </summary>
        private void IniSunnyUI()
        {
            //设置关联
            Header.TabControl = MainTabControl;
            //增加页面到Main，并自定义一个index
            try
            {
                AddPage(new Form_Auto(), 1001);//主界面

            }
            catch (Exception e)
            {
                MessageBox.Show($"From_Auto加载失败:{e.Message}");
                return;
            }

            try
            {
                AddPage(new Form_Set(), 1002);//设置
            }
            catch (Exception e)
            {
                MessageBox.Show($"Form_Set加载失败:{e.Message}");
                return;
            }

            try
            {
                AddPage(new Form_MainParamSet(), 1003);//参数
            }
            catch (Exception e)
            {
                MessageBox.Show($"Form_MainParamSet加载失败:{e.Message}");
                return;
            }

            try
            {
                AddPage(new Form_Module(), 1004);//模组

            }
            catch (Exception e)
            {
                MessageBox.Show($"Form_Module加载失败:{e.Message}");
                return;
            }

            try
            {
                AddPage(new OtherDevice.OtherDeviceForm(), 1005);//系统设置
            }
            catch (Exception e)
            {
                MessageBox.Show($"OtherDeviceForm加载失败:{e.Message}");
                return;
            }
            try
            {
                AddPage(new SystemSet(), 1006);//外部设备
            }
            catch (Exception e)
            {
                MessageBox.Show($"SystemSet加载失败:{e.Message}");
                return;
            }

            //设置Header节点索引
            //将index绑定节点
            Header.Nodes[0].Text = "主页".Trim();
            Header.SetNodePageIndex(Header.Nodes[0], 1001);
            Header.SetNodeSymbol(Header.Nodes[0], 61461, 58);
            Header.SetNodePageIndex(Header.Nodes[1], 1002);
            Header.SetNodeSymbol(Header.Nodes[1], 61613, 58);
            // Header.Nodes[0].Text = "主窗体".tr();
            Header.Nodes[1].Text = "调试".Trim();
            Header.SetNodePageIndex(Header.Nodes[2], 1003);
            Header.SetNodeSymbol(Header.Nodes[2], 61643, 58);
            Header.Nodes[2].Text = "参数".Trim();
            Header.SetNodePageIndex(Header.Nodes[3], 1004);
            Header.SetNodeSymbol(Header.Nodes[3], 61488, 58);
            Header.Nodes[3].Text = "模组".Trim();
            Header.SetNodePageIndex(Header.Nodes[4], 1005);
            Header.SetNodeSymbol(Header.Nodes[4], 61742, 58);
            Header.Nodes[4].Text = "设备".Trim();
            Header.SetNodePageIndex(Header.Nodes[5], 1006);
            Header.SetNodeSymbol(Header.Nodes[5], 61459, 58);
            Header.Nodes[5].Text = "系统".Trim();

            LanguageHelp.GetInstance().Load();
            LanguageHelp.GetInstance().Function_FormRegist(this);
            LanguageHelp.GetInstance().Funtion_TransLate();

            //显示默认界面
            Header.SelectedIndex = 0;

            sys.g_User = sys.g_User;
        }

        private void uiAvatar1_Click(object sender, EventArgs e)
        {
            Form_HYLogin frm = new Form_HYLogin();
            frm.TopMost = true;
            frm.ShowDialog();

            frm.Dispose();
        }
        public void FlushHandLine(StationState stationState, User user)
        {
            string infoState = "";
            switch (stationState)
            {
                case StationState.StationStateEmg:
                    infoState = "[运行状态:急停中]";
                    if (LanguageHelp.GetInstance().languageData.Type_LanguageType == LanguagesType.English)
                    {
                        infoState = "[RunState:EMG]";
                    }
                    break;
                case StationState.StationStatePause:
                    infoState = "[运行状态:暂停中]";
                    if (LanguageHelp.GetInstance().languageData.Type_LanguageType == LanguagesType.English)
                    {
                        infoState = "[RunState:Pas]";
                    }
                    break;
                case StationState.StationStateRun:
                    infoState = "[运行状态:运行中]";
                    if (LanguageHelp.GetInstance().languageData.Type_LanguageType == LanguagesType.English)
                    {
                        infoState = "[RunState:EMG]";
                    }
                    break;
                case StationState.StationStateStop:
                    infoState = "[运行状态:停止中]";
                    if (LanguageHelp.GetInstance().languageData.Type_LanguageType == LanguagesType.English)
                    {
                        infoState = "[RunState:EMG]";
                    }
                    break;
                case StationState.StationStateHoming:
                    infoState = "[运行状态:回零中]";
                    if (LanguageHelp.GetInstance().languageData.Type_LanguageType == LanguagesType.English)
                    {
                        infoState = "[RunState:Homing]";
                    }
                    break;
            }
            string strUserName = $"HYSoftFrame [用户：{user._userName} 登陆成功]";
            string strProductName = $" [当前产品：{ParamSetMgr.GetInstance().CurrentProductFile}]";
            if (LanguageHelp.GetInstance().languageData.Type_LanguageType == LanguagesType.English)
            {
                strUserName = $"HYSoftFrame [User：{user._userName} Login]";
                strProductName = $" [CurrentProduct：{ParamSetMgr.GetInstance().CurrentProductFile}]";
            }

            GlobalVariable.str_SoftVersion = $"{Param_System.Instance.机型._strParamVal}_{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")}_" +
                              $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()}";
            this.Text = "";
            this.Text = strUserName + infoState + strProductName + GlobalVariable.str_SoftVersion;
        }
        public void ChangedUserRight(User currentUserser)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => ChangedUserRight(currentUserser)));
            }
            else
            {
                int index = this.Text.IndexOf(":");
                switch (currentUserser._userRight)
                {
                    case UserRight.User_None:
                        Avatar.Symbol = 62020;
                        break;
                    case UserRight.Operator:
                        Avatar.Symbol = 62019;
                        break;
                    case UserRight.Debug:
                        Avatar.Symbol = 62018;
                        break;
                    case UserRight.Software:
                        Avatar.Symbol = 62017;
                        break;
                    case UserRight.Admin:
                        Avatar.Symbol = 62016;
                        break;
                    default:
                        break;
                }
                FlushHandLine(GlobalVariable.g_StationState, currentUserser);
                DynamicPassword.ChangeRight((int)currentUserser._userRight);
            }
        }
        private void Header_MenuItemClick(string itemText, int menuIndex, int pageIndex)
        {

        }
        /// <summary>
        /// 复位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void btnReset_Click(object sender, EventArgs e)
        {

            if (GlobalVariable.g_StationState == StationState.StationStateEmg
                || GlobalVariable.g_StationState == StationState.StationStateStop)
            {
                if (!UIMessageBox.ShowAsk("是否启动复位? 全机复位过程耗时较长!"))
                    return;
                DeviceDataCollect.GetInstance().Function_ControlLog("主界面", "全机回零");
                formHome = new Form_正在复位();
                formHome.TopMost = true;
                formHome.Show();
                formHome.InfoAndProcess("全机回零", 0);
                UserConfig.ResetIO();
                btnReset.Enabled = false;
                btnStart.Enabled = false;
                Header.SelectedIndex = 0;
                Header.MouseUp += Header_MouseUp;
                GlobalVariable.g_StationState = StationState.StationStateHoming;
                try
                {
                    StationStateHelper.OnTest_ShowStep("系统", "开始回零", LogType.Warn);
                    Task task = new Task(() =>
                    {
                        bool result = UserConfig.Function_全机回零();
                        if (result)
                        {
                            btnReset.FillColor = Color.FromArgb(80, 160, 255);
                            GlobalVariable.g_StationState = StationState.StationStateStop;
                            StationStateHelper.OnTest_ShowStep("系统", "回零成功", LogType.Info);
                        }
                        else
                        {
                            GlobalVariable.g_StationState = StationState.StationStateEmg;
                            StationStateHelper.OnTest_ShowStep("系统", "回零失败", LogType.Err);

                        }
                        BeginInvoke(new Action(() =>
                        {
                            Header.MouseUp -= Header_MouseUp;
                            btnReset.Enabled = true;
                            btnStart.Enabled = true;
                            formHome.bEn = result;
                            while (!formHome.IsDisposed)
                            {
                                Thread.Sleep(20);
                                Application.DoEvents();
                            }
                            GC.Collect();
                        }));

                    });
                    task.Start();
                }
                catch (Exception ex)
                {
                    StationStateHelper.OnTest_ShowStep("系统", "回零失败", LogType.Err);
                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                UIMessageBox.ShowWarning("请勿在运行状态下复位");
            }

        }

        private void Header_MouseUp(object sender, MouseEventArgs e)
        {
            Header.SelectedIndex = 0;

        }

        private  void btnStart_Click(object sender, EventArgs e)
        {
            if (GlobalVariable.g_ControlMode == ControlMode.Manual)
            {
                UIMessageBox.ShowError("手动状态下，禁止启动");
                return;
            }


            if (GlobalVariable.g_StationState == StationState.StationStateStop)
            {
                if (AlarmMgr.GetIntance().IsAlarm())
                {
                    UIMessageBox.ShowError("报警未清除，禁止启动");
                    return;
                }
                if (!IsSafeDoorAndGrating())
                    return;
                if(!UserConfig.Funtion_运行前处理())
                    return;
                if (!UIMessageBox.ShowAsk($"当前机台是否安全，是否可以启动?"))
                    return;
                BaseDll.DeviceDataCollect.GetInstance().Function_ControlLog("主界面", "自动运行");
                if(GlobalVariable.g_ControlMode== ControlMode.None)
                {
                    if (!UserConfig.Function_全机回零())
                    {
                        UIMessageBox.ShowError("全机回零失败，禁止启动");
                        return;
                    }
                }
                LoadSeverMgr.Instance.Start();
                StationMgr.GetInstance().Run();
            }
            else if (GlobalVariable.g_StationState == StationState.StationStateRun)
            {
                BaseDll.DeviceDataCollect.GetInstance().Function_ControlLog("主界面", "暂停运行");
                UserConfig.Funtion_暂停时处理();
                StationMgr.GetInstance().Pause();
            }
            else if (GlobalVariable.g_StationState == StationState.StationStatePause)
            {
                if(AlarmMgr.GetIntance().IsAlarm())
                {
                    UIMessageBox.ShowError("报警未清除，禁止启动");
                    return;
                }
                BaseDll.DeviceDataCollect.GetInstance().Function_ControlLog("主界面", "恢复运行");
                if (!IsSafeDoorAndGrating())
                    return;
                UserConfig.Funtion_恢复时处理();
                StationMgr.GetInstance().Resume();
            }
            else if (GlobalVariable.g_StationState == StationState.StationStateEmg)
            {
                UIMessageBox.ShowError("发生错误，请先复位");
            }
            else if (GlobalVariable.g_StationState == StationState.StationStateHoming)
            {
                UIMessageBox.ShowError("正在回零，请勿运行");
            }

        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (!UIMessageBox.ShowAsk("是否确定停止? "))
                return;
            BaseDll.DeviceDataCollect.GetInstance().Function_ControlLog("主界面", "停止运行");
            btnReset.Enabled = true;
            btnStart.Enabled = true;
            Header.MouseUp -= Header_MouseUp;
            StationMgr.GetInstance().Stop();
            UserConfig.Funtion_停止时处理();
            btnReset.FillColor = Color.Red;
        }

        private void btnClearAlarm_Click(object sender, EventArgs e)
        {
            AlarmMgr.GetIntance().StopAlarmBeet();
            for (int i = 0; i < 100; i++)
            {
                MotionMgr.GetInstace().ResetAxis(i);
            }
        }
        public void StationStateChangedHandler(StationState currState)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => StationStateChangedHandler(currState)));
            }
            else
            {
                switch (currState)
                {
                    case StationState.StationStatePause:
                        btnStart.Symbol = 61515;
                        btnStart.Selected = true;
                        break;
                    case StationState.StationStateHoming:
                        btnStart.Symbol = 61515;
                        btnStart.Selected = false;
                        break;
                    case StationState.StationStateRun:
                        btnStart.Symbol = 61516;
                        btnStart.Selected = false;
                        break;
                    case StationState.StationStateStop:
                        btnStart.Symbol = 61515;
                        btnStart.Selected = false;
                        break;
                    case StationState.StationStateEmg:
                        btnStart.Symbol = 61515;
                        btnStart.Selected = false;
                        break;
                }
                FlushHandLine(currState, sys.g_User);

            }
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            AlarmMgr.GetIntance().StopAlarmBeet();
            if (!this.ShowAskDialog("是否退出程序！", UIStyle.Gray))
            {
                e.Cancel = true;
                return;
            }

        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Environment.Exit(0);
            UserConfig.CloseHardWork();
        }
        private void Btn_LightModule_Click(object sender, EventArgs e)
        {
            try
            {
                Dictionary<string, ParamSet> systemPatams = ParamSetMgr.GetInstance().GetFields<ParamSet>(Param_System.Instance);
                Dictionary<string, ParamSet> SelectedItems = systemPatams.Where(t => t.Value.b_IsStartCheck).ToDictionary((t) => t.Key, (v) => v.Value);
                Dictionary<string, Dictionary<string, ParamSet>> dic_CheckParam = new Dictionary<string, Dictionary<string, ParamSet>>();
                dic_CheckParam.Add("系统", SelectedItems);
                foreach (var item in StationMgr.GetInstance().GetDicStaion())
                {
                    dic_CheckParam.Add(item.Value.Name, item.Value.GetCheckParam());
                }
                if (SelectedItems != null && SelectedItems.Count > 0)
                {
                    FormInfoBeforeStart formInfoBeforeStart = new FormInfoBeforeStart(dic_CheckParam);

                    formInfoBeforeStart.TopMost = true;
                    formInfoBeforeStart.TopLevel = true;
                    formInfoBeforeStart.WindowState = FormWindowState.Normal;

                    formInfoBeforeStart.ShowDialog();

                    if (!formInfoBeforeStart.bSure)
                    {
                        formInfoBeforeStart.Dispose();
                        btnStart.Enabled = true;
                        return;
                    }
                    formInfoBeforeStart.Dispose();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
